#include <iostream>
#include <fcntl.h>
#include <unistd.h>
#include <cerrno>
#include <cstring>

using namespace std;

void SetNonBlock(int fd)
{
    int fl = fcntl(fd, F_GETFL);
    fcntl(fd, F_SETFL, fl | O_NONBLOCK);
}

// 非阻塞的文件读，0文件描述符
int main()
{
    SetNonBlock(0);
    char buffer[1024];
    while (true)
    {
        sleep(1);

        errno = 0;
        ssize_t sz = read(0, buffer, sizeof(buffer));
        if (sz > 0)
        {
            buffer[sz - 1] = 0;
            cout << "#echo: " << buffer << "errno:" << errno << "strerror:" << strerror(errno) << endl;
        }
        else
        {
            if (errno == EWOULDBLOCK || errno == EAGAIN)
            {
                cout << "当前0文件描述符还没有就绪,再等一下吧" << endl;
                continue;
            }
            else if (errno == EINTR)
            {
                cout << "当前0文件描述符读被信号中断了,再等一下吧" << endl;
                continue;
            }
            else
            {
                // 错误处理
                cout << "errno:" << errno << "strerror:" << strerror(errno) << endl;
            }
        }
    }
    return 0;
}